<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <input
      type="file"
      accept="image/*"
      capture="camera"
      multiple
      id="selector"
    />
    <button id="upload">Upload</button>
    <button id="upload1">Upload11111</button>

    <div id="status"></div>
    <script>
      // const LOCAL_IP = '192.168.105.71';
      const LOCAL_IP = 'localhost';

      document.getElementById('upload').addEventListener('click', () => {
        upload();
      });
      document.getElementById('upload1').addEventListener('click', () => {
        upload1();
      });

      function upload1() {
        let files = document.getElementById('selector').files;
        const file = files[0];
        const formData = new FormData();
        formData.append('file', file);
        fetch(`http://${LOCAL_IP}:3005/api/minio/upload`, {
          method: 'POST',
          body: formData,
        }).then(async (res) => {
          const dataJson = await res.json();
          console.log('dataJson');
          console.log(dataJson);
          // const imgSrc = `http://${LOCAL_IP}:9000/xf-bucket/${file.name}`;
          document.querySelector('#status').innerHTML += `
          <div>
                      <h2> ${dataJson.url} </h2>
            <img src='${dataJson.url}' >
            </div>`;
        });
      }

      function upload() {
        let files = document.getElementById('selector').files;
        for (let i = 0; i < files.length; i++) {
          let file = files[i];
          retrieveNewURL(file, (file, url) => {
            uploadFile(file, url);
          });
        }
      }

      function retrieveNewURL(file, cb) {
        fetch('/api/minio/presignedUrl?name=' + file.name)
          .then((res) => res.text())
          .then((url) => {
            cb(file, url);
          });
      }

      function uploadFile(file, url) {
        // url = url.replace('localhost', LOCAL_IP);
        fetch(url, {
          method: 'PUT',
          body: file,
        }).then((res) => {
          const imgSrc = `http://${LOCAL_IP}:6002/xf-bucket/${file.name}`;
          document.querySelector('#status').innerHTML += `
          <h2> ${imgSrc} </h2>
            <img src='${imgSrc}' >`;
        });
      }
    </script>
  </body>
</html>
